﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Studio77.PopBall.Core;
using Studio77.PopBall.Utils;
using OpenXLive;
using Microsoft.Phone.Tasks;
using UmengSDK;
using System.ComponentModel;
using System.Windows.Threading;

namespace Studio77.PopBall
{
    public partial class MainPage : PhoneApplicationPage
    {
        private static bool isShowOpenAd = false;

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            isOnGift = false;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);


            //清除页面堆栈
            try
            {
                for (int i = 0; i < 4; i++)
                {
                    NavigationService.RemoveBackEntry();
                }
            }
            catch
            { }

            //动画
            StoryboardBall1.RepeatBehavior = RepeatBehavior.Forever;
            StoryboardBall1.Begin();

            StoryboardBall2.RepeatBehavior = RepeatBehavior.Forever;
            StoryboardBall2.Begin();

            StoryboardBall3.RepeatBehavior = RepeatBehavior.Forever;
            StoryboardBall3.Begin();

            StoryboardBall4.RepeatBehavior = RepeatBehavior.Forever;
            StoryboardBall4.Begin();

            StoryboardBall5.RepeatBehavior = RepeatBehavior.Forever;
            StoryboardBall5.Begin();

            this.txtHighScore.Text = StageManager.Instance.HighScore.ToString();

            //继续游戏判断逻辑
            if (StageManager.Instance.SaveData != null)
            {
                this.btnContinue.IsEnabled = true;
                this.txtContinueInfo.Visibility = System.Windows.Visibility.Visible;
                this.txtContinueInfo.Text = "关卡-" + StageManager.Instance.SaveData.StageIndex;
            }
            else
            {
                this.btnContinue.IsEnabled = false;
                this.txtContinueInfo.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (StageManager.Instance.IsPlaySound)
            {
                this.btnSoundOn.Visibility = System.Windows.Visibility.Visible;
                this.btnSoundOff.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                this.btnSoundOn.Visibility = System.Windows.Visibility.Collapsed;
                this.btnSoundOff.Visibility = System.Windows.Visibility.Visible;
            }


            //播放背景音乐
            AudioPlayHelper.PlayBackground();

            //启动线程，刷新广告状态
            UpdateAdType();

            this.btnGift.Visibility = System.Windows.Visibility.Collapsed;
            if (StageManager.Instance.IsDoNewUserTask)
            {
                this.btnGift.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if (UmengSDK.UmengAnalytics.GetOnlineParam("useGift") == "1")
            {
                this.btnGift.Visibility = System.Windows.Visibility.Visible;
            }

            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if ((usemokaStr == "1" || usemokaStr == "3") && !isShowOpenAd)
            {
                isShowOpenAd = true;
                DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromSeconds(1);
                timer.Tick += (object ss, EventArgs ee) =>
                {
                    timer.Stop();
                    string dateStr = DateTime.Now.ToString("yyyyMMdd") + (DateTime.Now.Hour < 12 ? "A" : "P");
                    if (StageManager.Instance.LastFullScreenDate != dateStr)
                    {
                        StageManager.Instance.LastFullScreenDate = dateStr;
                        NavigationService.Navigate(new Uri("/Game77SharedLib;component/MokaPage.xaml?channel=ppq", UriKind.RelativeOrAbsolute));
                    }
                };
                timer.Start();

            }
        }

        private void UpdateAdType()
        {
            if (!StageManager.Instance.isLoadAdType)
            {
                #region Umeng方式

                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += (object ss, DoWorkEventArgs ee) =>
                {
                    try
                    {
                        String AdTypeValue = UmengAnalytics.GetOnlineParam("AdType");
                        int adTypeIntValue = 1;
                        if (int.TryParse(AdTypeValue, out adTypeIntValue))
                        {
                            StageManager.Instance.AdType = adTypeIntValue;
                        }
                        else
                        {
                            StageManager.Instance.AdType = 1;
                        }
                    }
                    catch (Exception)
                    {

                    }

                    //String useNewUserStr = UmengAnalytics.getConfigParams("useNewUser");
                    //int useNewUserIntValue = 0;
                    //if (int.TryParse(useNewUserStr, out useNewUserIntValue))
                    //{
                    //    StageManager.Instance.UseNewUser = useNewUserIntValue;
                    //}
                    //else
                    //{
                    //    StageManager.Instance.UseNewUser = 0;
                    //}
                };
                bw.RunWorkerAsync();





                #endregion

                #region 自己链接百度云的方式


                //    WPWebClient wPWebClient = new WPWebClient();
                //    WPRequestData rData = new WPRequestData()
                //    {
                //        requestMethod = RequestMethod.METHOD_GET,
                //        httpUrl = "http://1.tyydwpsupport.duapp.com/popballcnAdType.php",
                //        isNeedCache = false,
                //        timeOut = "10",
                //    };

                //    wPWebClient.OnDownLoadDataCompleted = (object sender_a, DownloadStringCompletedEventArgs e_a) =>
                //    {
                //        try
                //        {
                //            //异常情况
                //            if (e_a.Error != null)
                //            {

                //            }//正常流程
                //            else if (!e_a.Cancelled && null != e_a.Result)
                //            {
                //                string resultString = e_a.Result;
                //                int resultAdType = int.Parse(resultString.Trim());
                //                StageManager.Instance.AdType = resultAdType;
                //            }
                //        }
                //        catch (Exception ex)
                //        {
                //            StageManager.Instance.AdType = 1;
                //        }

                //    };
                //    wPWebClient.Connection(rData, true);
                //    StageManager.Instance.isLoadAdType = true;


                #endregion

            }

        }

        private void Button_Click_1(object sender, System.Windows.RoutedEventArgs e)
        {
            bool isStart = true;
            if (StageManager.Instance.SaveData != null)
            {
                if (MessageBox.Show("确定重新开始游戏？之前的游戏进度会丢失", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    isStart = false;
                }
            }
            if (isStart)
            {
                SoundManager.PlayEffect(SoundManager.buttonClick);
                StageManager.Instance.LaunchCount++;
                // 在此处添加事件处理程序实现。
                this.NavigationService.Navigate(new Uri("/Pages/GamePage.xaml?IsNewGame=1", UriKind.RelativeOrAbsolute));
            }
        }

        private void btnContinue_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            StageManager.Instance.LaunchCount++;
            // 在此处添加事件处理程序实现。
            this.NavigationService.Navigate(new Uri("/Pages/GamePage.xaml?IsNewGame=0", UriKind.RelativeOrAbsolute));
        }

        private void btnOpenxlive_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            if (XLiveGameManager.CurrentSession != null && XLiveGameManager.CurrentSession.IsValid)
            {
                OpenXLive.Silverlight.XLiveUIManager.ShowGameCenter();
            }
        }

        private void btnSoundOn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //关闭音效
            StageManager.Instance.IsPlaySound = false;
            AudioPlayHelper.StopBackground();
            this.btnSoundOn.Visibility = System.Windows.Visibility.Collapsed;
            this.btnSoundOff.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnSoundOff_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //打开音效
            StageManager.Instance.IsPlaySound = true;
            AudioPlayHelper.PlayBackground();
            this.btnSoundOn.Visibility = System.Windows.Visibility.Visible;
            this.btnSoundOff.Visibility = System.Windows.Visibility.Collapsed;
        }

        bool isOnGift = false;

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (isOnGift)
            {
                this.StoryboardHidePackage.Begin();
                isOnGift = false;
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }

        private void btnGift_Click_1(object sender, RoutedEventArgs e)
        {
            isOnGift = true;
            this.StoryboardShowPackage.Begin();
        }

        private void btnGetMB_Click_1(object sender, RoutedEventArgs e)
        {
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
            StageManager.Instance.IsCommented = true;
            StageManager.Instance.IsDoNewUserTask = true;

            //增加30个魔法球
            StageManager.Instance.MagicBallCount += 30;

            this.btnGetMB.Content = "已领取";
            this.btnGetMB.IsEnabled = false;
            this.btnGift.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnCloseGift_Click_1(object sender, RoutedEventArgs e)
        {
            isOnGift = false;
            this.StoryboardHidePackage.Begin();
        }
    }
}